/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatserver;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tiphanie
 */
//classe qui represente les clients qui sont connectes
public class Client extends Thread {
    
    //TODO: Client disconnect/user logout -> remove from users list
    
    Socket socket;
    OnlineUser user;
    
    void setOnlineUser(OnlineUser newUser) {
        user = newUser;
        ChatServer.users.add(newUser);
    }
    
    public Client(Socket s){
        this.socket = s;
    }

    //mettre le tout dans un bloc while(true), mais ne fonctionne pas
    //la méthode du thread
    @Override
    public void run() {
        try {

            //pour écrire sur le socket
            PrintWriter writeStringOnSocket = new PrintWriter(
                    new BufferedWriter(
                    new OutputStreamWriter(this.socket.getOutputStream())),
                    true);

            //pour lire sur le socket
            BufferedReader readStringFromSocket = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

            //lire l'action choisie par le client sur socket
            String action = readStringFromSocket.readLine();
            if (action.equals("create")) {
                //chek si username existe deja
                String username;
                do {
                    //read username
                    username = readStringFromSocket.readLine();
                    writeStringOnSocket.println("usernameNotFree");
                } while (!ChatServer.database.CheckUsernameFree(username));
                writeStringOnSocket.println("usernameAccepted");

                //read password
                String password = readStringFromSocket.readLine();
                
                //TODO: read the rest of the user data
                //TODO: create new user in the database
                setOnlineUser(new OnlineUser(username));
            }
            
            if (action.equals("login")) {
                //read username
                String username = readStringFromSocket.readLine();
                //read password
                String password = readStringFromSocket.readLine();
                
                //TODO: check user/password combination in the database
                //TODO: if wrong, ask again 2 more times, then disconnect
                setOnlineUser(new OnlineUser(username));
            }
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
